import fs from 'fs';
import path from 'path';
export default class PageRequire {
    constructor() {
        this._pagePath = path.join(process.cwd(), '/src/shared');

    }

    earchPages(_path) {
        var files = fs.readdirSync(_path, {encoding: 'utf8'});
        return files;
    }

    createPages() {
        var that = this;
        try {
            var result = {};
            that.create(result, that.earchPages(path.join(that._pagePath, 'pages')), "pages", "");
            //console.log('最终结果：', result);

            return result;
        } catch (error) {
            console.log(error);
            return {};
        }
    }

    create(result, files, _path, _subPath) {
        var that = this;
        _subPath = _subPath.replace('\\', "/");
        for (var i = 0; i < files.length; i++) {
            var item = files[i];
            var basePath = path.join(that._pagePath, _path, item);
            var stat = fs.lstatSync(basePath);
            if (stat.isDirectory()) {
                result[item] = {};
                that.create(result[item], that.earchPages(basePath), _path + "/" + item, path.join(_subPath, item).toString());
            } else {
                var name = item;
                name = name.substring(0, name.lastIndexOf('.'));

                result[name] = require("pages/" + (!!_subPath ? _subPath + "/" : "") + item.substring(0, item.lastIndexOf('.')));
            }
        }
    }
}
